package com.mjfeed.controller.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mjfeed.controller.BaseController;
import com.mjfeed.dto.api.CartItemListJSON;
import com.mjfeed.dto.api.MemberJSON;
import com.mjfeed.dto.api.OrderJSON;
import com.mjfeed.dto.api.OrderListJSON;
import com.mjfeed.dto.api.ProductListJSON;
import com.mjfeed.dto.api.ReceiverJSON;
import com.mjfeed.dto.api.ReceiverListJSON;
import com.mjfeed.entity.Area;
import com.mjfeed.entity.Cart;
import com.mjfeed.entity.CartItem;
import com.mjfeed.entity.Member;
import com.mjfeed.entity.Order;
import com.mjfeed.entity.PaymentMethod;
import com.mjfeed.entity.Product;
import com.mjfeed.entity.Receiver;
import com.mjfeed.entity.ShippingMethod;
import com.mjfeed.service.AreaService;
import com.mjfeed.service.CartItemService;
import com.mjfeed.service.CartService;
import com.mjfeed.service.MemberService;
import com.mjfeed.service.OrderService;
import com.mjfeed.service.PaymentMethodService;
import com.mjfeed.service.ProductService;
import com.mjfeed.service.ReceiverService;
import com.mjfeed.service.ShippingMethodService;
import com.mjfeed.util.Format;
import com.mjfeed.util.Md5Util;
import com.mjfeed.util.Pagination;
import com.mjfeed.util.ParamBean;
import com.mjfeed.util.QueryCondition;

/**
 * @description 会员
 * @author zhaominglei
 * @date 2014年12月9日
 */
@Controller("apiMemberController")
@RequestMapping("/api/member")
public class MemberController extends BaseController {
	@Resource(name = "memberService")
	private MemberService memberService;
	@Resource(name="orderService")
	private OrderService orderService;
	@Resource(name="receiverService")
	private ReceiverService receiverService;
	@Resource(name="areaService")
	private AreaService areaService;
	@Resource(name="cartService")
	private CartService cartService;
	@Resource(name="cartItemService")
	private CartItemService cartItemService;
	@Resource(name="productService")
	private ProductService productService;
	@Resource(name="paymentMethodService")
	private PaymentMethodService paymentMethodService;
	@Resource(name="shippingMethodService")
	private ShippingMethodService shippingMethodService;
	
	@RequestMapping(value = "/register", method=RequestMethod.POST)
	public String register(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		Member member = new Member();
		member.setName(paramBean.getName());
		member.setUsername(paramBean.getUsername());
		member.setMobile(paramBean.getUsername());
		member.setEmail(paramBean.getEmail());
		member.setPassword(paramBean.getPassword());
		member.setIsEnabled(true);
		member.setIsLocked(false);
		member.setLoginFailureCount(0);
		member.setLockedDate(null);
		member.setRegisterIp(super.getRemoteIpAddr(request));
		member.setLoginIp(super.getRemoteIpAddr(request));
		member.setLoginDate(new Date());
		memberService.save(member);
		
		//注册成功后 返回MD5加密的串 username=username&password=password
		MemberJSON memberJSON = memberService.memberToJSON(member);
		super.renderJson(response, memberJSON);
		return null;
	}
	
	@RequestMapping(value = "/login", method=RequestMethod.POST)
	public String login(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getPassword())) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		if (!paramBean.getPassword().equals(pMember.getPassword())) {
			return null;
		}
		//校验成功后 返回MD5加密的串 username=username&password=password
		MemberJSON memberJSON = memberService.memberToJSON(pMember);
		super.renderJson(response, memberJSON);
		return null;
	}
	
	@RequestMapping(value = "/order", method=RequestMethod.GET)
	public String order(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		
		if (checkSign(pMember, paramBean.getSign())) {
			paramBean.setUrl(getBasePath(request) + "api/member/order.shtml");
			int p = (Format.null2Zero(request.getParameter("p")) == 0) ? 1 : Format.null2Zero(request.getParameter("p"));
			paramBean.setPage(p);
			paramBean.setPageSize(APP_DEFAULT_PAGE_SIZE);
			Pagination<Order> pagination = orderService.getPagination(paramBean, pMember);
			OrderListJSON orderListJSON = orderService.searchToJSON(pagination);
			super.renderJson(response, orderListJSON);
		}
		return null;
	}
	
	@RequestMapping(value = "/order/create", method=RequestMethod.POST)
	public String orderCreate(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())
				|| paramBean.getCartId() == null || paramBean.getCartId().longValue() < 1
				|| paramBean.getReceiverId() == null || paramBean.getReceiverId().longValue() < 1
				|| paramBean.getPaymentMethodId() == null || paramBean.getPaymentMethodId().longValue() < 1
				|| paramBean.getShippingMethodId() == null || paramBean.getShippingMethodId().longValue() < 1) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		
		if (checkSign(pMember, paramBean.getSign())) {
			Cart cart = cartService.getById(Cart.class, paramBean.getCartId());
			if (cart == null) {
				return null;
			}
			Receiver receiver = receiverService.getById(Receiver.class, paramBean.getReceiverId());
			if (receiver == null) {
				return null;
			}
			PaymentMethod paymentMethod = paymentMethodService.getById(PaymentMethod.class, paramBean.getPaymentMethodId());
			if (paymentMethod == null) {
				return null;
			}
			ShippingMethod shippingMethod = shippingMethodService.getById(ShippingMethod.class, paramBean.getShippingMethodId());
			if (shippingMethod == null) {
				return null;
			}
			Order order = orderService.create(cart, receiver, paymentMethod, shippingMethod, paramBean.getIsInvoice(), paramBean.getInvoiceinfo(), null, null);
			OrderJSON orderJSON = orderService.beanToJSON(order);
			super.renderJson(response, orderJSON);
		}
		return null;
	}
	
	@RequestMapping(value = "/receiver", method=RequestMethod.GET)
	public String receiver(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		
		if (checkSign(pMember, paramBean.getSign())) {
			List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
			queryConditions.add(new QueryCondition("member", QueryCondition.EQ, pMember));
			String orderBy = "order by id desc";
			List<Receiver> receivers = receiverService.get(Receiver.class, queryConditions, orderBy, 1, APP_DEFAULT_PAGE_SIZE);
			ReceiverListJSON receiverListJSON = receiverService.searchToJSON(receivers);
			super.renderJson(response, receiverListJSON);
		}
		return null;
	}
	
	@RequestMapping(value = "/receiver/add", method=RequestMethod.POST)
	public @ResponseBody String receiverAdd(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		
		if (checkSign(pMember, paramBean.getSign())) {
			Receiver receiver = new Receiver();
			receiver.setMember(pMember);
			receiver.setAddress(paramBean.getAddress());
			Area area = areaService.getById(Area.class, paramBean.getAreaId());
			receiver.setAddress(paramBean.getAddress());
			receiver.setArea(area);
			receiver.setAreaName(area.getFullName());
			receiver.setConsignee(paramBean.getConsignee());
			receiver.setIsDefault(paramBean.getIsDefault());
			receiver.setPhone(paramBean.getPhone());
			receiver.setZipCode(paramBean.getZipCode());
			receiverService.save(receiver);
			return "true";
		}
		return null;
	}
	
	@RequestMapping(value = "/receiver/update", method=RequestMethod.POST)
	public @ResponseBody String receiverUpdate(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())
				|| paramBean.getReceiverId() == null || paramBean.getReceiverId() < 0 ) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		
		if (checkSign(pMember, paramBean.getSign())) {
			Receiver receiver = receiverService.getById(Receiver.class, paramBean.getReceiverId());
			if (receiver == null) {
				return null;
			}
			receiver.setMember(pMember);
			receiver.setAddress(paramBean.getAddress());
			Area area = areaService.getById(Area.class, paramBean.getAreaId());
			receiver.setAddress(paramBean.getAddress());
			receiver.setArea(area);
			receiver.setAreaName(area.getFullName());
			receiver.setConsignee(paramBean.getConsignee());
			receiver.setIsDefault(paramBean.getIsDefault());
			receiver.setPhone(paramBean.getPhone());
			receiver.setZipCode(paramBean.getZipCode());
			receiverService.update(receiver);
			return "true";
		}
		return null;
	}
	
	@RequestMapping(value = "/receiver/getdefault", method=RequestMethod.GET)
	public String receiverGetdefault(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		
		if (checkSign(pMember, paramBean.getSign())) {
			Receiver result = null;
			Set<Receiver> receivers = pMember.getReceivers();
			for (Receiver receiver : receivers) {
				if (receiver.getIsDefault() != null && receiver.getIsDefault()) {
					result = receiver;
					break;
				}
			}
			ReceiverJSON receiverJSON = receiverService.beanToJSON(result);
			super.renderJson(response, receiverJSON);
		}
		return null;
	}
	
	@RequestMapping(value = "/favorite", method=RequestMethod.GET)
	public String favorite(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		
		if (checkSign(pMember, paramBean.getSign())) {
			Set<Product> products = pMember.getFavoriteProducts();
			ProductListJSON productListJSON = productService.favoritesToJSON(products);
			super.renderJson(response, productListJSON);
		}
		return null;
	}
	
	@RequestMapping(value = "/favorite/add", method=RequestMethod.POST)
	public @ResponseBody String favoriteAdd(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())
				|| paramBean.getProductId() == null || paramBean.getProductId().intValue() < 1) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		
		if (checkSign(pMember, paramBean.getSign())) {
			Product product = productService.getById(Product.class, paramBean.getProductId());
			if (product == null) {
				return null;
			}
			if (pMember.getFavoriteProducts().contains(product)) {
				return "true";
			}
			if (pMember.getFavoriteProducts().size() == Member.MAX_FAVORITE_COUNT) {
				return null;
			}
			pMember.getFavoriteProducts().add(product);
			memberService.update(pMember);
			return "true";
		}
		return null;
	}
	
	@RequestMapping(value = "/favorite/delete", method=RequestMethod.POST)
	public @ResponseBody String favoriteDelete(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())
				|| paramBean.getProductId() == null || paramBean.getProductId().intValue() < 1) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		
		if (checkSign(pMember, paramBean.getSign())) {
			Product product = productService.getById(Product.class, paramBean.getProductId());
			if (product == null) {
				return null;
			}
			if (!pMember.getFavoriteProducts().contains(product)) {
				return "true";
			}
			pMember.getFavoriteProducts().remove(product);
			memberService.update(pMember);
			return "true";
		}
		return null;
	}
	
	@RequestMapping(value = "/favorite/check", method=RequestMethod.POST)
	public @ResponseBody String favoriteCheck(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())
				|| paramBean.getProductId() == null || paramBean.getProductId().intValue() < 1) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		
		if (checkSign(pMember, paramBean.getSign())) {
			Product product = productService.getById(Product.class, paramBean.getProductId());
			if (product == null) {
				return null;
			}
			if (pMember.getFavoriteProducts().contains(product)) {
				return "true";
			}
		}
		return null;
	}
	
	@RequestMapping(value = "/update", method=RequestMethod.POST)
	public @ResponseBody String memberUpdate(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		
		if (checkSign(pMember, paramBean.getSign())) {
			pMember.setEmail(pMember.getEmail());
			pMember.setName(paramBean.getName());
			memberService.update(pMember);
			return "true";
		}
		return null;
	}
	
	@RequestMapping(value = "/updatepass", method=RequestMethod.POST)
	public @ResponseBody String memberUpdatepass(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		if (!paramBean.getPassword().equals(pMember.getPassword())) {
			return null;
		}
		if (checkSign(pMember, paramBean.getSign())) {
			pMember.setPassword(paramBean.getnPassword());
			memberService.update(pMember);
			return "true";
		}
		return null;
	}
	
	/**
	 * 上传和下载购物车数据
	 */
	@RequestMapping(value = "/cart/sync", method=RequestMethod.POST)
	public String cartSync(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		if (checkSign(pMember, paramBean.getSign())) {
			Set<CartItem> cartItems = cartService.sync(pMember, paramBean.getCartData());
			CartItemListJSON cartItemListJSON = cartService.searchToJSON(cartItems);
			super.renderJson(response, cartItemListJSON);
		}
		return null;
	}
	
	/**
	 * 更新购物车
	 */
	@RequestMapping(value = "/cart/update", method=RequestMethod.POST)
	public @ResponseBody String cartUpdate(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())
				|| paramBean.getCartItemData() == null) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		if (checkSign(pMember, paramBean.getSign())) {
			cartService.update(pMember, paramBean.getCartItemData());
			return "true";
		}
		return null;
	}
	
	/**
	 * 删除购物车
	 */
	@RequestMapping(value = "/cart/delete", method=RequestMethod.POST)
	public @ResponseBody String cartDelete(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || StringUtils.isBlank(paramBean.getUsername()) || StringUtils.isBlank(paramBean.getSign())
				|| paramBean.getCartItemData() == null) {
			return null;
		}
		Member pMember = memberService.getMemberByUsername(paramBean.getUsername());
		if (pMember == null) {
			return null;
		}
		if (checkSign(pMember, paramBean.getSign())) {
			cartService.delete(pMember, paramBean.getCartItemData());
			return "true";
		}
		return null;
	}
	
	private boolean checkSign(Member member, String sign) {
		boolean flag = false;
		if (member == null || StringUtils.isBlank(sign)) {
			return flag;
		}
		StringBuilder descSign = new StringBuilder();
		descSign.append("username=").append(member.getUsername()).append("&password=").append(member.getPassword());
		if (sign.equals(Md5Util.encrypt(descSign.toString()))) {
			flag = true;
		}
		return flag;
	}

}
